import {Component, Injector, OnInit, PipeTransform, ViewChild} from '@angular/core';
import {NzCascaderOption, NzFormatEmitEvent, NzMessageService, NzTreeComponent, NzTreeNodeOptions} from 'ng-zorro-antd';
import {FormBuilder} from '@angular/forms';
import {FetchService} from '../../core/net/fetch.service';
import {Pipe} from '@angular/core';
import {MtMngBureauComponent} from './mt-mng-bureau/mt-mng-bureau.component';
import {MtIrrigatedComponent} from './mt-irrigated/mt-irrigated.component';
import {MtMngStationComponent} from './mt-mng-station/mt-mng-station.component';
import {MtInletGateComponent} from './mt-inlet-gate/mt-inlet-gate.component';
import {MtControlGateComponent} from './mt-control-gate/mt-control-gate.component';
import {MtReturnGateComponent} from './mt-return-gate/mt-return-gate.component';
import {MtStraightGateComponent} from './mt-straight-gate/mt-straight-gate.component';
import {MtPumpStationComponent} from './mt-pump-station/mt-pump-station.component';
import {MtSmallPumpStComponent} from './mt-small-pump-st/mt-small-pump-st.component';
import {MtMainCanalComponent} from './mt-main-canal/mt-main-canal.component';
import {MtMainSubCanalComponent} from './mt-main-sub-canal/mt-main-sub-canal.component';
import {MtSubCanalComponent} from './mt-sub-canal/mt-sub-canal.component';
import {MtCulvertComponent} from './mt-culvert/mt-culvert.component';
import {MtAqueductComponent} from './mt-aqueduct/mt-aqueduct.component';
import {MtDropComponent} from './mt-drop/mt-drop.component';
import {MtOverflowWeirComponent} from './mt-overflow-weir/mt-overflow-weir.component';
import {MtBridgeComponent} from './mt-bridge/mt-bridge.component';
import {MtDrainComponent} from './mt-drain/mt-drain.component';
import {GeneralSettings} from "./GeneralSettings";
import {MtSectionComponent} from "./mt-section/mt-section.component";
import {MtWellComponent} from "./mt-well/mt-well.component";
import {MtFloodComponent} from "./mt-flood/mt-flood.component";
import {MtFloodDetentionComponent} from "./mt-flood-detention/mt-flood-detention.component";
import {Regions} from "../one-map/one-map";
import {SearchMaintainService} from "./search-maintain.service";
import * as _ from 'lodash';
import { UniversalService } from 'src/app/core/util/universal.service';

const IrrigatedTypeMap = {
    '1': '自流灌区',
    '2': '扬水灌区'
};
const treeNodesData = [
    {
        title: '灌区',
        key: '1',
        isLeaf: true
    },
    {
        title: '管理机构',
        key: '2',
        selectable: false,
        children: [
            {
                title: '宁西公司',
                key: '2-1',
                isLeaf: true
            },
            {
                title: '管理所',
                key: '2-2',
                isLeaf: true
            }
        ]
    },
    {
        title: '渠道',
        key: '3',
        selectable: false,
        children: [
            {
                title: '干渠',
                key: '3-1',
                isLeaf: true
            },
            {
                title: '支干渠',
                key: '3-2',
                isLeaf: true
            },
            {
                title: '支渠',
                key: '3-3',
                isLeaf: true
            }
        ]
    },
    {
        title: '闸门',
        key: '4',
        selectable: false,
        children: [
            {
                title: '进水闸',
                key: '4-1',
                isLeaf: true
            },
            {
                title: '节制闸',
                key: '4-2',
                isLeaf: true
            },
            {
                title: '退水闸',
                key: '4-3',
                isLeaf: true
            },
            {
                title: '直开口闸',
                key: '4-4',
                isLeaf: true
            }
        ]
    },
    {
        title: '泵站',
        key: '5',
        selectable: false,
        children: [
            {
                title: '泵站',
                key: '5-1',
                isLeaf: true
            },
            {
                title: '小扬抽',
                key: '5-2',
                isLeaf: true
            }
        ]
    },
    {
        title: '建筑物',
        key: '6',
        selectable: false,
        children: [
            {
                title: '涵洞',
                key: '6-1',
                isLeaf: true
            },
            {
                title: '渡槽',
                key: '6-2',
                isLeaf: true
            },
            {
                title: '跌水',
                key: '6-3',
                isLeaf: true
            },
            {
                title: '溢流堰',
                key: '6-4',
                isLeaf: true
            },
            {
                title: '桥梁',
                key: '6-5',
                isLeaf: true
            }
        ]
    },
    // {
    //     title: '排水沟',
    //     key: '7',
    //     isLeaf: true
    // },
    // {
    //     title: '抗旱机井',
    //     key: '8',
    //     isLeaf: true
    // },
    {
        title: '山洪沟',
        key: '9',
        isLeaf: true
    },
    // {
    //     title: '滞洪区',
    //     key: '10',
    //     isLeaf: true
    // },
    {
        title: '监测断面',
        key: '11',
        isLeaf: true
    }
];

@Component({
  selector: "app-search-maintain",
  templateUrl: "./search-maintain.component.html",
  styleUrls: ["./search-maintain.component.scss"]
})
export class SearchMaintainComponent implements OnInit {
  mngType = [
    { label: "管理处", value: "0", checked: true },
    { label: "管理所", value: "1" }
  ];
  areaType = [
    { label: "市", value: "0" },
    { label: "区县", value: "1", checked: true }
  ];
  canalType = [
    { label: "干渠", value: "mainCanal", checked: true },
    { label: "支渠", value: "subCanal" }
  ];
  @ViewChild("objTreeComponent") objTreeComponent: NzTreeComponent;

  objNodes: NzTreeNodeOptions[] = treeNodesData;
  compsHash = {
    "1": {
      comp: MtIrrigatedComponent,
      params: {
        type: 1,
        name: "灌区"
      }
    },
    "2-1": {
      comp: MtMngBureauComponent,
      params: {
        type: 1,
        name: "管理处"
      }
    },
    "2-2": {
      comp: MtMngStationComponent,
      params: {
        type: 1,
        name: "管理所"
      }
    },
    "3-1": {
      comp: MtMainCanalComponent,
      params: {
        type: 1,
        name: "干渠"
      }
    },
    "3-2": {
      comp: MtMainSubCanalComponent,
      params: {
        type: 1,
        name: "支干渠"
      }
    },
    "3-3": {
      comp: MtSubCanalComponent,
      params: {
        type: 1,
        name: "支渠"
      }
    },
    "4-1": {
      comp: MtInletGateComponent,
      params: {
        type: 1,
        name: "进水闸"
      }
    },
    "4-2": {
      comp: MtControlGateComponent,
      params: {
        type: 1,
        name: "节制闸"
      }
    },
    "4-3": {
      comp: MtReturnGateComponent,
      params: {
        type: 1,
        name: "退水闸"
      }
    },
    "4-4": {
      comp: MtStraightGateComponent,
      params: {
        type: 1,
        name: "直开口闸"
      }
    },
    "5-1": {
      comp: MtPumpStationComponent,
      params: {
        type: 1,
        name: "泵站"
      }
    },
    "5-2": {
      comp: MtSmallPumpStComponent,
      params: {
        type: 1,
        name: "小扬抽"
      }
    },
    "6-1": {
      comp: MtCulvertComponent,
      params: {
        type: 1,
        name: "涵洞"
      }
    },
    "6-2": {
      comp: MtAqueductComponent,
      params: {
        type: 1,
        name: "渡槽"
      }
    },
    "6-3": {
      comp: MtDropComponent,
      params: {
        type: 1,
        name: "跌水"
      }
    },
    "6-4": {
      comp: MtOverflowWeirComponent,
      params: {
        type: 1,
        name: "溢流堰"
      }
    },
    "6-5": {
      comp: MtBridgeComponent,
      params: {
        type: 1,
        name: "桥梁"
      }
    },
    // "7": {
    //   comp: MtDrainComponent,
    //   params: {
    //     type: 1,
    //     name: "排水沟"
    //   }
    // },
    // "8": {
    //   comp: MtWellComponent,
    //   params: {
    //     type: 1,
    //     name: "抗旱机井"
    //   }
    // },
    "9": {
      comp: MtFloodComponent,
      params: {
        type: 1,
        name: "山洪沟"
      }
    },
    "10": {
      comp: MtFloodDetentionComponent,
      params: {
        type: 1,
        name: "滞洪区"
      }
    },
    "11": {
      comp: MtSectionComponent,
      params: {
        type: 1,
        name: "监测断面"
      }
    }
  };
  currentNode = "1"; //  默认选中灌区对象

  mngSelected = [];
  regions = Regions;
  regionSelected: any;
  stationId = ""; //  管理处编码
  sectionId = ""; //  管理所编码
  adcd = null; //  行政区划编码
  private injectors = {};

  constructor(
    private fb: FormBuilder,
    private fetchService: FetchService,
    private message: NzMessageService,
    private searchService: SearchMaintainService,
    private inj: Injector,
    private universalService: UniversalService
  ) {}

  ngOnInit() {
    const userInfo = this.universalService.getUserProfile() || {};
    this.stationId =
          userInfo["manageId"] == "10001" ? "" : userInfo["manageId"];
    this.mngSelected = [this.stationId];
    this.searchService.regionMngDataChange.next({
      sectionId: '',
      stationId: this.stationId,
      adcd: ''
    });
  }

  checkboxChanged(): void {}

  onChangeRegion(values: string[]): void {
    console.log(values);
    this.adcd = values.length ? _.last(values) : "";
    this.searchService.regionMngDataChange.next({
      sectionId: this.sectionId,
      stationId: this.stationId,
      adcd: this.adcd
    });
  }

  loadData(node: NzCascaderOption, index: number): PromiseLike<void> {
    return new Promise(resolve => {
      if (index < 0) {
        // if index less than 0 it is root node
        this.fetchService
          .post("wrs/wrsBmanage/list", {
            type: 1, //  管理处
            id: this.stationId,
            pageSize: 10000
          })
          .subscribe(res => {
            node.children = res["list"].map(item => {
              return {
                value: item.id,
                // value: item.manageCode,
                label: item.manageName
              };
            });
            resolve();
          });
      } else if (index === 0) {
        this.fetchService
          .post("wrs/wrsBmanage/list", {
            pid: node.value,
            type: 2, //  管理所
            pageSize: 10000
          })
          .subscribe(res => {
            node.children = res["list"].map(item => {
              return {
                value: item.id,
                label: item.manageName,
                isLeaf: true
              };
            });
            resolve();
          });
      }
    });
  }

  onChangeMng(values: string[]): void {
    console.log(values);
    this.stationId = values.length > 0 ? values[0] : "1";
    this.sectionId = values.length > 1 ? values[1] : "";
    this.searchService.regionMngDataChange.next({
      sectionId: this.sectionId,
      stationId: this.stationId,
      adcd: this.adcd
    });
  }

  nzClick(event: NzFormatEmitEvent): void {
    console.log(event);
    const nodeClick = event.node;
    if (!nodeClick.isLeaf) {
      nodeClick.isExpanded = !nodeClick.isExpanded;
      this.checkNodeExpand(nodeClick);
    } else {
      this.currentNode = event.node.key;
      nodeClick.isChecked = true;
    }
  }

  onExpand(event) {
    this.checkNodeExpand(event.node);
  }

  checkNodeExpand(nodeClick) {
    const list = this.objTreeComponent.getExpandedNodeList();
    list.map(node => {
      if (node.key != nodeClick.key) {
        node.isExpanded = false;
      }
    });
  }

  getInjector(id) {
    console.log(id);
    let inject = this.injectors[id];
    if (!inject) {
      inject = Injector.create(
        [{ provide: GeneralSettings, useValue: this.compsHash[id].params }],
        this.inj
      );
      this.injectors[id] = inject;
    }

    return inject;
  }
}

@Pipe({
    name: 'IrrigatedType'
})
export class IrrigatedTypePipe implements PipeTransform {
    transform(value: string) {
        return IrrigatedTypeMap[value];
    }
}

